<template>
  <div class="jqr">
    <van-nav-bar
        class="app-nav-bar"
        title="小智同学"
        left-arrow
        @click-left="$router.back()"
    />
    <van-cell-group ref="message-list">
      <van-cell :title="message.msg" v-for="(message,index) in messages"  :key="index"/>
    </van-cell-group>
    <div class="article-bottom">
      <van-field v-model="message" placeholder="请输入内容" />
      <van-button class="comment-btn" type="default" size="small" @click="onSend">发送</van-button>
    </div>
  </div>
</template>

<script>
import io from 'socket.io-client'
import {setItem,getItem} from "@/utils/storage";
//收发消息
// socket.emit('消息类型','消息内容')
// socket.on('event',function(data){})
export default {
  name: "jqr",
  data(){
    return{
      message:'',
      socket:null,
      messages:getItem('toutiao-message')||[]
    }
  },
  watch:{
    messages(){
      setItem('toutiao-message',this.messages)
      this.$nextTick(()=>{
        this.scrollTpBottom()
      })
    }
  },
  created() {
    //建立连接
    const socket=io('http://ttapi.research.itcast.cn',{
      query: {
        token: getItem('toutiao-user').token
      }
    })
    this.socket=socket
    socket.on('connect', ()=>{
      console.log('连接建立成功');
    })

    socket.on('disconnect', ()=>{
      console.log('断开连接');
    })

    socket.on('message', (data)=>{
      this.messages.push(data)
    })
  },
  methods:{
    onSend(){
      const data={
        msg:this.message,
        timestamp:Date.now()
      }
      this.socket.emit('message',data)
      this.messages.push(data)
      this.message=''
    },
    scrollTpBottom(){
      const list=this.$refs['message-list']
      list.scrollTop=list.scrollHeight
    }
  }
}
</script>

<style scoped lang="less">
.app-nav-bar{
  background-color: #3a8ee6;
  position:fixed;
  left: 0;
  right: 0;
  top: 0;
}
/deep/.van-icon-arrow-left{
  color: #ffffff;
}
/deep/.van-nav-bar__title{
  color: #ffffff;
}
.van-cell-group{
  position: fixed;
  left: 0;
  right: 0;
  top: 46px;
  bottom: 44px;
  overflow-y: auto;
}
.article-bottom{
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 40px;
  background-color: #ffffff;
  display: flex;
  justify-content: space-around;
  align-items: center;
  font-size: 22px;
  padding: 0 14px;
  .comment-btn{
    width: 100px;
    background-color:#3a8ee6;
    color: #ffffff;
  }
}
</style>